const { Sequelize, DataTypes } = require('sequelize');
const configFactory = require('./config/config.default.js');
const appInfo = { name: 'test' };
const config = configFactory(appInfo).sequelize;

// 创建 Sequelize 实例
const sequelize = new Sequelize(config.database, config.username, config.password, {
  host: config.host,
  port: config.port,
  dialect: config.dialect,
  logging: false
});

// 定义采购订单模型
const PurchaseOrder = sequelize.define('purchase_order', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  orderNumber: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true,
    field: 'order_number'
  },
  supplierId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    field: 'supplier_id'
  },
  shopName: {
    type: DataTypes.STRING(200),
    allowNull: true,
    field: 'shop_name'
  },
  purchaser: {
    type: DataTypes.STRING(50),
    allowNull: true
  },
  orderDate: {
    type: DataTypes.DATE,
    allowNull: false,
    field: 'order_date'
  },
  expectedDeliveryDate: {
    type: DataTypes.DATE,
    allowNull: true,
    field: 'expected_delivery_date'
  },
  totalAmount: {
    type: DataTypes.DECIMAL(15, 2),
    allowNull: false,
    field: 'total_amount'
  },
  status: {
    type: DataTypes.STRING(20),
    defaultValue: 'pending',
    allowNull: false
  },
  remark: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  organizationId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    field: 'organization_id'
  },
  createdAt: {
    type: DataTypes.DATE,
    field: 'created_at'
  },
  updatedAt: {
    type: DataTypes.DATE,
    field: 'updated_at'
  }
}, {
  tableName: 'purchase_orders',
  timestamps: true,
  underscored: true
});

async function debugUpdateLogic() {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 查找一个 shopName 为 NULL 的订单
    const existingOrder = await PurchaseOrder.findOne({
      where: { shopName: null }
    });
    
    if (!existingOrder) {
      console.log('没有找到 shopName 为 NULL 的订单');
      return;
    }
    
    console.log('找到的订单:');
    console.log('订单号:', existingOrder.orderNumber);
    console.log('当前 shopName:', existingOrder.shopName);
    console.log('当前 remark:', existingOrder.remark);
    
    // 模拟要更新的新订单数据
    const newOrderData = {
      shopName: '测试店铺名称',
      remark: '淘宝进货单 - 测试店铺名称'
    };
    
    console.log('\n新订单数据:');
    console.log('shopName:', newOrderData.shopName);
    console.log('remark:', newOrderData.remark);
    
    // 检查更新条件
    console.log('\n更新条件检查:');
    console.log('!existingOrder.shopName:', !existingOrder.shopName);
    console.log('newOrderData.shopName:', !!newOrderData.shopName);
    console.log('条件结果:', !existingOrder.shopName && newOrderData.shopName);
    
    if (!existingOrder.shopName && newOrderData.shopName) {
      console.log('\n满足更新条件，执行更新...');
      await PurchaseOrder.update({
        shopName: newOrderData.shopName,
        remark: newOrderData.remark
      }, {
        where: { orderNumber: existingOrder.orderNumber }
      });
      
      console.log('更新完成');
      
      // 查询更新后的结果
      const updatedOrder = await PurchaseOrder.findOne({
        where: { orderNumber: existingOrder.orderNumber }
      });
      
      console.log('\n更新后的订单:');
      console.log('订单号:', updatedOrder.orderNumber);
      console.log('shopName:', updatedOrder.shopName);
      console.log('remark:', updatedOrder.remark);
    } else {
      console.log('\n不满足更新条件，跳过更新');
    }
  } catch (error) {
    console.error('操作失败:', error);
  } finally {
    await sequelize.close();
  }
}

// 运行测试
debugUpdateLogic();